import axios from 'axios'
import { sign } from '@/components/machine-verification/hooks/signBySecretKey'
import qs from 'qs'
/**
 * 实例化axios
 * @param baseUrl 请求基地址
 * @param ContentType 请求头 content-type
 */
export function createMachineVerifyAxiosInstance(
  baseUrl = import.meta.env.VITE_CAPTCHA_API,
  ContentType = 'application/x-www-form-urlencoded;charset=utf-8'
) {
  const instance = axios.create({
    baseURL: baseUrl,
    timeout: 9000,
    withCredentials: false,
    headers: {
      'Content-Type': ContentType
    }
  })
  // 添加请求拦截器
  instance.interceptors.request.use(
    function (config) {
      if (config.url?.includes('/captcha/get') || config.url?.includes('/captcha/check')) {
        sign(config)
      }
      config.data = qs.stringify(config.data)
      return config
    },
    function (error) {
      // 对请求错误做些什么
      return Promise.reject(error)
    }
  )

  // 添加响应拦截器
  instance.interceptors.response.use(
    function (response) {
      return response.data
    },
    function (error) {
      // 超出 2xx 范围的状态码都会触发该函数。
      // 对响应错误做点什么
      return Promise.reject(error)
    }
  )
  return instance
}
export const machineVerifyAxiosInstance = createMachineVerifyAxiosInstance()
